# -*- coding:utf-8 -*-
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.cache import Cache
from flask.ext.script import Manager
from flask.ext.migrate import Migrate
from flask_wtf.csrf import CsrfProtect
from flask.ext.mail import Mail
from config import LOG_DIR
from flask_login import LoginManager
from flask.ext.themes import setup_themes


def CreateApp():
    app = Flask(__name__)
    app.config.from_object('config')
    SetLog(app)
    return app


def SetCsrf(app=None):
    csrf = CsrfProtect()
    csrf.init_app(app)
    return csrf


def SetLoginManager(app):
    from models import AnonymousUser

    lm = LoginManager()
    lm.init_app(app)
    lm.anonymous_user = AnonymousUser
    lm.session_protection = 'strong'
    lm.login_view = 'user.login'
    lm.login_message = u"请先登录"
    return lm


def SetCache(app):
    '''设置缓存'''
    cache = Cache(app)
    return cache


def SetManager(app):
    '''控制台'''
    manager = Manager(app)
    return manager


def SetMigrate(app, db):
    '''数据库迁移'''
    migrate = Migrate(app, db)
    return migrate


#: 注册蓝图
def Register_Blueprint(app, pages):
    for prefix, view in pages:
        app.register_blueprint(view, url_prefix=prefix)


def configurator(app, db):
    from golsee import models
    from models import Permission

    @app.context_processor
    def info():
        info = models.Blog_info.info()
        blog_name = models.Settings.query.filter(models.Settings.type == 'blog_name',
                                                 models.Settings.is_use == 1).first().value
        return dict(visit_all=info.visit_all,
                    visit_day=info.visit_day,
                    visit_month=info.visit_month,
                    visit_attack=info.visit_attack,
                    visit_attack_day=info.visit_attack_day,
                    visit_robot=info.visit_robot,
                    visit_robot_day=info.visit_robot_day,
                    article_all=info.article_all,
                    article_month=info.article_month,
                    user_all=info.user_all,
                    login_all=info.login_all,
                    blog_name=blog_name)

    @app.context_processor
    def top_ten():
        art = models.Article.top(10)
        return dict(top_ten=art)

    @app.context_processor
    def month_count():
        count = models.Article.count_by_month()
        return dict(month_count=count)

    @app.context_processor
    def first_bar():
        bar = models.Settings.first_bar()
        return dict(first_bar=bar)

    @app.context_processor
    def admin_second_bar():
        bar = models.Settings.admin_second_bar()
        return dict(admin_second_bar=bar)

    @app.context_processor
    def admin_user():
        admin_role = models.Role.query.filter_by(permissions=0xff).first()
        admin = models.User.query.filter_by(role=admin_role.id).first()
        return dict(admin_name=admin.nicename,
                    admin_img=admin.avatar(20),
                    admin_info=admin.info)

    @app.context_processor
    def inject_permissions():
        return dict(Permission=Permission)


def SetLog(app):
    '''日志设置'''
    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler

        file_handler = RotatingFileHandler(LOG_DIR + '/golsee.log', 'a', 1 * 1024 * 1024, 10)
        file_handler.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        app.logger.setLevel(logging.INFO)
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
        app.logger.info('golsee startup')


golsee = CreateApp()
db = SQLAlchemy(golsee)
mymail = Mail()
cache = SetCache(golsee)
csrf = SetCsrf(golsee)
lm = SetLoginManager(golsee)
setup_themes(golsee, app_identifier='golsee')
migrate = SetMigrate(golsee, db)
manager = SetManager(golsee)
configurator(golsee, db)
from _main import main
from _user import user
from _article import article
from _api import api
from _admin import admin
from . import error
pages = [
    ('/', main),
    ('/user', user),
    ('/article', article),
    ('/api', api),
    ('/admin/', admin),
]
Register_Blueprint(golsee, pages)